import { Card, Form, Select, Input, Button, Table, message } from "antd";
import { useEffect, useState } from "react";
import { SearchOutlined } from "@ant-design/icons";
import type { ColumnsType } from "antd/lib/table";
import {
  reqGetCityOrDistrictList,
  reqGetHospitalList,
  reqGetProvinceList,
  reqUpdateHospitalStatus,
} from "@/api/hospital/hospitalList";
import {
  HospitalItemType,
  HospitalListType,
  ProvinceList,
  Status,
} from "@/api/hospital/model/hospitalListTypes";
import { useNavigate } from "react-router-dom";

const { Option } = Select;
function HospitalList() {
  // 定义医院分页列表相关state
  const [hospitalList, setHospitalList] = useState<HospitalListType>([]); //医院列表的数据
  const [current, setCurrent] = useState(1); //当前页码
  const [pageSize, setPageSize] = useState(5); //每页展示数量
  const [total, setTotal] = useState(0); //总数
  const [loading, setLoading] = useState(false); //设置加载中loading
  const [provinceList, setProvinceList] = useState<ProvinceList>([]); //省份列表
  const [cityList, setCityList] = useState<ProvinceList>([]); //市列表
  const [districtList, setDistrictList] = useState<ProvinceList>([]); //区列表
  //定义医院类型列表的数据
  const [hosTypeList, setHosTypeList] = useState<ProvinceList>([]);
  //定义点击"查看"按钮跳转路由的hook
  const navigate = useNavigate();

  //表单对象
  const [form] = Form.useForm();

  //获取医院列表
  const getHospitalList = async (page = current, limit = pageSize) => {
    //读取表单的值, 将其传入请求函数参数对象中
    const values = form.getFieldsValue();
    //请求时显示loading
    setLoading(true);
    //更新页码和每页的展示数量
    setCurrent(page);
    setPageSize(limit);
    //请求api接口获取数据
    const result = await reqGetHospitalList({ page, limit, ...values });
    // console.log(result);
    //请求数据成功后更新数据
    setHospitalList(result.content);
    setTotal(result.totalElements);
    setLoading(false); // 请求成功后隐藏loading
  };

  //清空输入的条件
  const reset = () => {
    // 清空输入/选择的数据
    form.resetFields();
    // 将城市和区的列表数据清空
    setCityList([]);
    setDistrictList([]);
    //重新请求医院列表数据
    getHospitalList();
  };

  //跳转到医院详情页
  const goHospitalShow = (id: string) => {
    return () => {
      navigate(`/syt/hospital/hospitalList/show/${id}`);
    };
  };

  //点击上线或下线按钮
  const updateHospitalStatus = (id: string, status: Status) => {
    return async () => {
      //请求上线下线的api（传递两个参数，医院id和医院上下线状态）
      await reqUpdateHospitalStatus(id, status);
      //更新状态提示
      message.success("更新状态成功！");
      //重新请求医院列表没有必要，只需更新单个数据即可
      const newHospital = hospitalList.map((item) => {
        if (item.id === id) {
          item.status ? (item.status = 0) : (item.status = 1);
        }
        return item;
      });
      //更新完单个医院上下线状态后设置最新的医院列表数据
      setHospitalList(newHospital);
    };
  };
  // 当省份发生变化，获取对应的城市数据
  const getCityList = async (id: number) => {
    //请求api接口获取市/区数据
    const res = await reqGetCityOrDistrictList(id);
    //  console.log(res);
    setCityList(res); //设置市状态
    // 将选中的市和区值清空
    form.setFieldsValue({ cityCode: undefined, districtCode: undefined });
    //将区列表数据清空
    setDistrictList([]);
  };

  // 当市发生变化，获取对应的区数据
  const getDistrictList = async (id: number) => {
    const res = await reqGetCityOrDistrictList(id);
    //  console.log(res);
    setDistrictList(res);

    // 将选中的市和区值清空
    form.setFieldsValue({ districtCode: undefined });
  };
  //初始化获取分页列表的显示
  useEffect(() => {
    getHospitalList();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  //初始化加载省份列表展示
  useEffect(() => {
    const getProvinceList = async () => {
      const res = await reqGetProvinceList();
      // console.log(res);
      setProvinceList(res); //将请求成功的省份列表设置为状态
    };
    getProvinceList();
  }, []);

  // 初始化获取医院类型列表
  useEffect(() => {
    const getHosTypeList = async () => {
      //医院类型的id固定为10000
      const result = await reqGetCityOrDistrictList(10000);
      // console.log(result);
      setHosTypeList(result);
    };
    getHosTypeList();
  }, []);

  //表格表头信息的数据
  const columns: ColumnsType<HospitalItemType> = [
    {
      title: "序号",
      width: 70,
      align: "center",
      render: (x: any, y: any, index: number) => {
        return index + 1;
      },
    },
    {
      title: "医院logo",
      align: "center",
      //当设置 dataIndex 时,第一参数 就是 dataIndex 值
      //当不设置 dataIndex 时,第一个参数是当前的一行数据对象
      dataIndex: "logoData", //将dataIndex改为对应的数据字段
      render: (logo: string) => {
        //base64图片
        return (
          <img
            src={`data:image/jpeg;base64,${logo}`}
            style={{ width: "100px", height: "100px" }}
            alt="logo"
          />
        );
      },
    },
    {
      title: "医院名称",
      dataIndex: "hosname",
      align: "center",
    },
    {
      title: "等级",
      align: "center",
      render: (data: HospitalItemType) => {
        return data.param.hostypeString;
      },
    },
    {
      title: "详细地址",
      align: "center",
      render: (data: HospitalItemType) => {
        return data.param.fullAddress;
      },
    },
    {
      title: "状态",
      dataIndex: "status",
      align: "center",
      render: (status: Status) => {
        return status === 0 ? "未上线" : "已上线";
      },
    },
    {
      title: "创建时间",
      dataIndex: "createTime",
      align: "center",
    },
    {
      title: "操作",
      width: 250,
      align: "center",
      fixed: "right",
      render: (row) => {
        return (
          <>
            <Button type="primary" onClick={goHospitalShow(row.id)}>
              查看
            </Button>
            <Button type="primary" className="ml">
              排班
            </Button>
            {row.status === 0 ? (
              <Button
                type="primary"
                className="ml"
                onClick={updateHospitalStatus(row.id, 1)}
              >
                上线
              </Button>
            ) : (
              <Button
                type="primary"
                className="ml"
                danger
                onClick={updateHospitalStatus(row.id, 0)}
              >
                下线
              </Button>
            )}
          </>
        );
      },
    },
  ];
  return (
    <Card>
      {/* 头部表单 */}
      <Form layout="inline" form={form} onReset={reset}>
        <Form.Item style={{ marginBottom: 20 }} name="provinceCode">
          <Select
            placeholder="请选择省"
            style={{ width: 200 }}
            onChange={getCityList}
          >
            {provinceList.map((item) => {
              return (
                <Option key={item.id} value={item.value}>
                  {item.name}
                </Option>
              );
            })}
          </Select>
        </Form.Item>

        <Form.Item style={{ marginBottom: 20 }} name="cityCode">
          <Select
            placeholder="请选择市"
            style={{ width: 200 }}
            onChange={getDistrictList}
          >
            {cityList.map((item) => {
              return (
                <Option key={item.id} value={item.value}>
                  {item.name}
                </Option>
              );
            })}
          </Select>
        </Form.Item>

        <Form.Item style={{ marginBottom: 20 }} name="districtCode">
          <Select placeholder="请选择区" style={{ width: 200 }}>
            {districtList.map((item) => {
              return (
                <Option key={item.id} value={item.value}>
                  {item.name}
                </Option>
              );
            })}
          </Select>
        </Form.Item>

        <Form.Item style={{ marginBottom: 20 }} name="hosname">
          <Input placeholder="医院名称" />
        </Form.Item>

        <Form.Item style={{ marginBottom: 20 }} name="hoscode">
          <Input placeholder="医院编号" />
        </Form.Item>

        <Form.Item style={{ marginBottom: 20 }} name="hostype">
          <Select placeholder="医院类型" style={{ width: 200 }}>
            {hosTypeList.map((item) => {
              return (
                <Option key={item.id} value={item.value}>
                  {item.name}
                </Option>
              );
            })}
          </Select>
        </Form.Item>

        <Form.Item style={{ marginBottom: 20 }} name="status">
          <Select placeholder="医院状态" style={{ width: 200 }}>
            {/* 注意要使用jsx语法，才会是number类型 */}
            <Option value={0}>未上线</Option>
            <Option value={1}>已上线</Option>
          </Select>
        </Form.Item>

        <Form.Item style={{ marginBottom: 20 }}>
          <Button
            onClick={() => getHospitalList()}
            type="primary"
            icon={<SearchOutlined />}
          >
            查询
          </Button>
          <Button className="ml" htmlType="reset">
            清空
          </Button>
        </Form.Item>
      </Form>

      {/* 表格和分页器 */}
      <Table
        rowKey={"id"}
        columns={columns}
        dataSource={hospitalList}
        bordered
        pagination={{
          current,
          pageSize,
          total,
          showQuickJumper: true,
          showSizeChanger: true,
          showTotal: (total) => `总共 ${total} 条`,
          onChange: getHospitalList,
          onShowSizeChange: getHospitalList,
        }}
        scroll={{ x: 1500 }}
        loading={loading}
      />
    </Card>
  );
}

export default HospitalList;
